/**
 * @Description:
 * @author 狮子
 * @since 2019/3/27
 */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Row, Col, Card, Button, Tabs, Form, Popconfirm, Modal,Select ,Tooltip} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'

// 当前组件样式
import styles from './manualAuthenticationStyle.less'
import { Grid, QueryCondition } from 'widget/Grid/index'
import { AdvanceSearch } from 'widget/CollapsiblePanels/index'
import Keypress  from 'widget/Keypress'
import { chunk,pick} from 'lodash'

import classnames from 'classnames/bind';
let cx = classnames.bind(styles);
const Option = Select.Option;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const routeView = function ({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const {modelObj, namespace} = model
  let {loading, btnLoading, modalObj, currentItem, queryList, tableData, pageConfig,statisticsInfo,tableModalData,query} = modelObj
  // modelObj.xxx获取model中状态机的值
  console.log('modelObj', modelObj)
 
  const columns = [
    {title: '合并时间', dataIndex: 'mergeTime', key: 'mergeTime',width:200},
    {title: '认证状态', dataIndex: 'authenticated', key: 'authenticated',width:100,render:function(item,idx){
      return item?<span>已认证</span>:<span>未认证</span>
    }},
    {title: '渠道信息', dataIndex: 'appId', key: 'appId',width:130,
    render:function (item, idx){
      if(item=='1000'){
        return <span>美的置业云</span>
      }else if(item=='1001'){
        return <span>销售系统标识</span>
      }else if(item == '1002'){
        return <span>案场系统标识</span>
      }else if(item=='1004'){
        return <span>智美分销</span>
      }
      
    }
   
  },
    {title: '姓名', dataIndex: 'name', key: 'name',width:130},
    {title: '证件类型', dataIndex: 'idCardType', key: 'idCardType',width:130,render:function(item,idx){
      return ['','身份证','台胞证','回乡证' ,'居住证','签证','护照','户口本','军官证','其他'][item]
    }},
    {title: '证件号码', dataIndex: 'idCardNo', key: 'idCardNo',},
    {title: '性别', dataIndex: 'gender', key: 'gender',width:80,render:function(item,idx){
      return ['女','男'][item]
    }},
    {title: '籍贯', dataIndex: 'birthPlace', key: 'birthPlace',width:80,},
    {title: '电话号码', dataIndex: 'mobile', key: 'mobile',width:130},
    {title: '联系方式', dataIndex: 'contacts', key: 'contacts',width:130 ,render:function(item,idx){
      return <div>
        {item && item.length ?item.join():null}
      </div>
    }},
    {title: '出生年月', dataIndex: 'birthday', key: 'birthday',width:130,
    render:function(item,idx){
      return <span>{item?item.substr(0,10):null}</span>
    }
  },
    {title: '教育程度', dataIndex: 'education', key: 'education',width:130 },
    {title: '所属行业', dataIndex: 'industry', key: 'industry',width:130 },
    {title: '所属区域', dataIndex: 'homeArea', key: 'homeArea',width:130 },
    {title: '工作区域', dataIndex: 'workArea', key: 'workArea',width:130 },
    {title: '地址', dataIndex: 'addresses', key: 'addresses',width:130,render:function(item,idx){
      return <Tooltip placement="topLeft" title={item && item.length?item.join():null }>
      <div>{item[0]}</div>
    </Tooltip>

    }},
    {title: '更新时间', dataIndex: 'editTime', key: 'editTime',width:200 },
  ]
  // 表格模板配置
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(columns, generateAction()),
      pageConfig, tableData
    },
    pageChange: (pageNo, pageSize) => {
      console.log(pageNo, pageSize)
      dispatch({ type: `${namespace}/pageChange`, payload: {pageNo, pageSize } });
    },
    scroll: {x: 2400},
    loading
  }
  const modalColumns = [
    {title: '姓名', dataIndex: 'names', key: 'names',width:210,render:function(item,obj){
      return common(item,'name')
        
    }},
    {title: '证件类型', dataIndex: 'idCardType', key: 'idCardType',width:130,render:function(item,obj){
      return <span>{['','身份证','台胞证','回乡证' ,'居住证','签证','护照','户口本','军官证','其他'][item]}</span>
    }},
    {title: '身份证号', dataIndex: 'idCardNo', key: 'idCardNo',width:130},
    {title: '电话号码', dataIndex: 'mobile', key: 'mobile',width:130},
    {title: '性别', dataIndex: 'genders', key: 'genders',width:80,render:function(item,idx){
      if(item && item.length>1){
        return <Select key={`${tableModalData.dataSource[0].gender}`} defaultValue={`${tableModalData.dataSource[0].gender}`} onChange={e=>{
          onchange(e,'gender')
        }}
                >
                  {item.map((val,idx)=>{
                  return <Option key={val}>{['女','男'][val]}</Option>
                })}
              </Select>
      }else{
        return <span>{['女','男'][item]}</span>
      }
    }},
    {title: '籍贯', dataIndex: 'birthPlaces', key: 'birthPlaces',width:130,render:function(item,idx){
      return common(item,'birthPlace')
    }},
    {title: '联系方式', dataIndex: 'contacts', key: 'contacts',width:210,render:function(item,obj){
      return <div>
        {item && item.length ?item.join():null}
      </div>
    }},
    {title: '出生年月', dataIndex: 'birthdays', key: 'birthday',width:130,render:function(item,obj){
      return common(item,'birthday')
    }},
    
    {title: '所属行业', dataIndex: 'industries', key: 'industries',width:130,render:function(item,obj){
      return common(item,'industry')
    }},
    {title: '教育程度', dataIndex: 'educations', key: 'educations',width:130,render:function(item,obj){
      return common(item,'education')
    }},
    {title: '所属区域', dataIndex: 'homeAreas', key: 'homeAreas',width:130,render:function(item,obj){
      return common(item,'homeArea')
      // console.log(item.length)
      // if(item && item.length>1){
      //   return <Select onChange={e=>{
      //     console.log(e)
      //     onchange(e,'homeAreas')
      //   }}
      //           >
      //             {item.map((val,idx)=>{
      //             return <Option key={val}>{val}</Option>
      //           })}
      //         </Select>
      // }else{
      //   return <span>{item}</span>
      // }
    }},
    {title: '工作区域', dataIndex: 'workAreas', key: 'workArea',width:130 ,render:function(item,obj){
      return common(item,'workArea')
    }},
    {title: '地址', dataIndex: 'addresss', key: 'addresss',width:200,render:function(item,obj){
      return <div>
                {/* {item && item.length && item.length>0?<span>{item[0]}</span>
              :null} */}
               {item && item.length ?item.join():null}
            </div>
    } },
    {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime',width:200 },
  ]
  const gridModalProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(modalColumns),
      // columns: modalColumns,
      pageConfig, 
      tableData:tableModalData
    },
    paginationFlag:false,
    scroll: {x: 1500},
    loading
  }
  //
  function common(item,name){
    if(item && item.length>1){
      if(name=='birthday'){
        item=item.map((i)=>{
          let  m=i.substr(0,10)
          return m
        })
      }
      console.log(tableModalData.dataSource)
      return <Select key={`${tableModalData.dataSource[0].gender}`} defaultValue={name=='birthday'&&tableModalData.dataSource[0][name]?tableModalData.dataSource[0][name].substr(0,10):`${tableModalData.dataSource[0][name]}`} onChange={e=>{
        onchange(e,name)
      }}
              >
                {item.map((val,idx)=>{
                return <Option key={val} >{val}</Option>
              })}
            </Select>
    }else{
      return <span>{name=='birthday' && item[0]?item[0].substr(0,10):item[0]}</span>
    }
  }
  // 表格操作区域 备案列表  启用  停用
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      render: (data, item, index) => {
        return (
          <div>
            
            {!item.authenticated?(<span>
              <a onClick={() =>{
                // updateModal({item,index})
                dispatch({
                  type:`${namespace}/confimManual`,payload:{...item}
                })
              }}>认证</a>
            </span>):( <div>
              <span>
              <a onClick={() =>{
                // updateModal({item,index})
                dispatch({
                  type:`${namespace}/cancelManual`,payload:{...item}
                })
              }}>取消认证</a>{<span className="ant-divider "/>}
            </span>
            <span>
            <a onClick={() =>{
              updateModal('修改',{item,index})
            }}>修改</a>
          </span>
          </div>
            )}
          </div>
        )
      }
    }
  }
//选择框
function onchange(e,name){
  console.log(e)
  dispatch({
    type: `${namespace}/updateStore`,
    payload: {
        query: {
            ...query,
            [name]:e,
        }
    }
})
}
  // 弹窗
  function updateModal (type,{item, index} = {}) {

    
    modalObj.visible = !modalObj.visible
    console.log(modalObj.visible)
    // currentItem = item
    // console.log('updateModal', item, index)
    if (item) {
      dispatch({
        type: `${namespace}/getManualDetail`,
        payload: {...item,index,modalObj}
      })
    }
    if(type=='保存'){
      dispatch({
        type: `${namespace}/confirmChange`,
        payload: {modalObj}
      })
  }
  dispatch({
    type: `${namespace}/updateStore`,
    payload: {modalObj}
  })
}
  
  
  //修改状态
  const changeState = (payload) => {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {...payload}
    })
  }
  //查询
  const onSearch = (payload={}) => {
    dispatch({
      type: `${namespace}/search`,
      payload
    })
  }
  
  return (
    <div className={cx('pageLayout')}>
      {/*监控键盘事件，自动刷新数据*/}
      <Keypress keyCode={13} cbk={()=>{
        onSearch();
      }} />
      
      <div className="public_listMain">
        <AdvanceSearch
          footer={
            <span>
                <Button type="primary" htmlType="submit" onClick={() => onSearch()} loading={modelObj.loading}>搜索</Button>
                <Button onClick={() => dispatch({ type: `${namespace}/queryReset` })}>重置</Button>
              </span>
          }>
          <QueryCondition
            data={queryList}
            inputChange={(key, value) => dispatch({type: `${namespace}/inputChange`, payload: {key, value}})}
          />
        </AdvanceSearch>
        {/* 表格区域 */}
        <div className="boxShadow">
          
          {/* 添加用户 */}
          <Grid {...gridProps} />
        </div>
        
      </div>
      <Modal
        visible = {modalObj.visible}
        onCancel={() => {updateModal()

        }}
        onOk={()=>{updateModal('保存')}}
        width={1000}
        okText='保存'
      >
        <Grid {...gridModalProps} />
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))

